angular.module('chatRoom.ctrl', [])
    .controller("chatCtrl", chatCtrl);

chatCtrl.$inject = ['$scope', 'socket', 'randomColor', 'userService',
    'useIDB', 'localStorageService', 'IDBService', 'Popup'];

/* @ngInject */
function chatCtrl($scope, socket, randomColor, userService, useIDB, localStorageService, IDBService, Popup) {
    var messageWrapper = $('.message-wrapper');
    var test111 = $('#test111');
    //this
    //vm =this;

    $scope.useIDB = useIDB;
    //add by wzh 20160602 用于控制网络断开的时候,不让继续subit
    $scope.disconnected = false;
    $scope.myPlaceHoder = "说点儿什么呢?";

    $scope.loginInfo = {};//这是我自己
    //$scope.receiver = {};//这是对方 ,,在 setReceiver 选择,群聊的ID =0
    //by wzh 20160602 初始化的receiver 设置为 群聊,否则,必须点接收者
    $scope.receiver = {userID: 0, userName: "all", nickname: "所有人", color: "#000", $$hashKey: "object:10"}
    $scope.publicMessages = [];//群聊消息
    $scope.privateMessages = {};//私信消息
    $scope.messages = $scope.publicMessages;//默认显示群聊
    $scope.users = [];//
    $scope.friends = [];//有消息来往的朋友
    $scope.color = randomColor.newColor();//当前用户头像颜色


    $scope.deleteDB = deleteDB;
    $scope.login = login;
    $scope.scrollToBottom = scrollToBottom;
    $scope.postMessage = postMessage;
    $scope.setReceiver = setReceiver;

    function deleteDB(name) {
        IDBService.deleteDB(name);
    };

    function login() {
        //登录进入聊天室
        //by wzh 20160428,做几个假数据,待修改登录结构
        //客户端登陆只发送 userName和pwd,pwd待处理
        $scope.pwd = '888888';

        //这里useName和nickname混淆了,待处理
        socket.emit("addUser", {userName: $scope.nickname, pwd: $scope.pwd});
    };


    function scrollToBottom() {
        messageWrapper.scrollTop(messageWrapper[0].scrollHeight);
    };

    //这是 点击 发送消息 的处理，向服务器发送 addMessage ，
    //服务器没有给 我(发送方) 返回一个 状态报告？是不是socket.js里面处理了？，

    function postMessage() {
        $scope.timeStamp = new Date().toTimeString();
        console.log('$scope.timeStamp====' + $scope.timeStamp);
        var msg = {
            content: $scope.words,
            type: "normal",
            color: $scope.color,
            friend: $scope.receiver.userName,
            //add by wzh 20160531 加一个实际字段表示聊天对象
            //add by wzh 20160531 发出的的消息,friend = to ,即接收者
            fromID: $scope.loginInfo.userID,
            from: $scope.loginInfo.userName,
            toID: $scope.receiver.userID,
            to: $scope.receiver.userName,
            timeStamp: $scope.timeStamp
        };

        console.log(msg);
        var messageID123 = "message_";
        messageID123 = messageID123 + 'all';



        console.debug('发出时===='+ $scope.words);
        console.log(msg);
        console.log($scope.receiver);

        //查询 messages 对象使用的 userName,不使用ID
        //ID 自动增长的,不适合用于查询,待全部改成 userName 索引
        var rec = $scope.receiver.userName;
        if (rec != 'all') {  //私信
            //如果没有给他发过,新建立一个 privateMessages 数组
            if (!$scope.privateMessages[rec]) {
                $scope.privateMessages[rec] = [];
            }
            //如果有了,追加本次信息到该朋友
            $scope.privateMessages[rec].push(msg);

            //console.log('发出时====');
            //console.log($scope.privateMessages[rec]);

            //add by wzh 20160509 保存到 IDB
            if ($scope.useIDB)
                IDBService.saveMessages(msg);
            else
                setPrivateMessagesToLS(msg.from, msg.to, $scope.privateMessages[rec]);
        } else { //群聊
            $scope.publicMessages.push(msg);

            //add by wzh 20160509 保存到 IDB
            if ($scope.useIDB)
                IDBService.saveMessages(msg);
            else
                setPublicMessagesToLS($scope.publicMessages);
        }



        //add by wzh 20160513 保存到friends
        if (isInFriends($scope.receiver.userName, $scope.friends)) {
            console.log('老朋友啊 ==');
            //do nothing
        }
        else {
            console.log('新人 ==');
            userService.setFriends($scope.loginInfo.userName, $scope.friends);
        }

        if (rec !== $scope.loginInfo.userID) { //排除给自己发的情况
            //自己发给自己只在本地显示，不要发送到服务端，当然如果系统要求，可以放开
            //console.log('发出时=22222==msg=');
            //console.log(msg);
            socket.emit("addMessage", msg);
        }


        $scope.words = "";//清空底部输入的内容？是不是应该放在emit之后？待处理
        console.debug('结束时===='+ $scope.words);
        //test111.text("1234567890");
        //$("#test111").text("1234567890");
       // $("#test111").attr("value","");
        $("#test111").val("").focus();
        $(".emoji-wysiwyg-editor.form-control").html("");
        //$("#test").val("");
    };

    //点击某个用户 或者 群发，分成 私聊和公聊
    function setReceiver(receiver) {
        console.log('setReceiver ==');
        console.log(receiver);
        $scope.receiver = receiver;
        //$scope.toID = receiver.userID;
        $scope.toUserName = receiver.userName;

        //console.log('setReceiver toID---' + $scope.toID);
        //console.log($scope.receiver);
        if ($scope.toUserName != 'all') { //私信用户
            if (!$scope.privateMessages[$scope.toUserName]) {
                $scope.privateMessages[$scope.toUserName] = [];


                //setReceiver 成功之后,读取 LS 的这个朋友历史记录
                //by wzh 20160529 无论新的旧的,新的朋友可能上次你没有点进去过

                //add by wzh 20160509 读取 IDB,从 cursor 读出来,直接放进 array
                if ($scope.useIDB) {
                    IDBService.getMessages($scope.toUserName).then(function (result) {
                            console.log("result.length 999  === " + result.length);
                            if (result instanceof Array) {
                                for (var i = 0; i < result.length; i++) {
                                    console.log(result[i]);
                                    $scope.privateMessages[$scope.toUserName].push(result[i]);
                                }

                            }
                        }
                    );
                }
                else {
                    //使用 LS 处理
                    $scope.privateMessages[$scope.toUserName]
                        = getPrivateMessagesFromLS($scope.loginInfo.userName, $scope.receiver.userName);
                }


            }
            else {
                //不用初始化,不用再读取 LS
                //$scope.privateMessages[toUserName] = [];
            }

            //  console.log('1111111');
            //  console.log('$scope.toUserName ===');
            //  console.log($scope.toUserName);
            //   console.log($scope.privateMessages[$scope.toUserName]);
            $scope.messages = $scope.privateMessages[$scope.toUserName];

        } else {//广播
            $scope.messages = $scope.publicMessages;
        }

        //找到该用户,他的消息标记去掉 未读
        var user = userService.get($scope.users, $scope.toUserName, $scope.toUserName);
        if (user) {
            user.hasNewMessage = false;
        }
    };

    //收到登录结果---我自己的登陆结果，即emit("addUser" 到服务器之后的返回结果
    socket.on('userAddingResult', function (result) {
        console.log('用户登陆的结果---');
        console.log(result);
        if (result.result) {
            //这里分解 data 详细信息
            console.log('用户登陆的结果 ok ok ---');
            $scope.loginInfo = result.data;
            console.log($scope.loginInfo.hasLogined);
            console.log($scope.loginInfo);

            //add by wzh 20160514 登陆成功之后,读取friends
            $scope.friends = userService.getFriends($scope.loginInfo.userName);

            console.log('用户登陆的结果 111 ---');
            console.log($scope.friends);

            //登陆成功之后,初始化数据库
            $scope.dbName = IDBService.myDB.name + "_" + $scope.loginInfo.userID;
            //必须等待数据库成功
            IDBService.initDB($scope.dbName).then(function (result) {
                //add by wzh 20160603
                IDBService.myDB.db = result;

                $scope.userExisted = false;//这个似乎没什么用
                $scope.loginInfo.hasLogined = true;

                console.log('userAddingResult userAddingResult 222 ---');
                //userAddingResult 成功之后,首先读取 LS 的历史记录:群聊的
                //add by wzh 20160509 读取 IDB,从 cursor 读出来,直接放进 array
                if ($scope.useIDB) {
                    IDBService.getMessages('all').then(function (result) {
                            console.log("result.length 999  === " + result.length);
                            if (result instanceof Array) {
                                for (var i = 0; i < result.length; i++) {
                                    //console.log(result[i]);
                                    $scope.publicMessages.push(result[i]);
                                }

                            }
                        }
                    );
                }
                else {
                    $scope.publicMessages = getPublicMessagesFromLS();
                }

                //显示群聊,记住上次的朋友?待处理
                $scope.messages = $scope.publicMessages;
            });


        } else {//昵称被占用
            console.log('用户登陆的结果 : 已经登陆了---');
            $scope.userExisted = true;
        }
    });

    //接收到欢迎新用户消息---- 这是其他人的登陆结果，追加到本地的 user 列表
    socket.on('userAdded', function (data) {
        if (!$scope.loginInfo.hasLogined) return;
        console.log('userAdded userAdded 456  -data--');
        console.log(data);

        $scope.publicMessages.push({content: " " + data.nickname + " ", type: "welcome"});
        $scope.users.push(data);


    });

    //接收到在线用户消息 ---- 这是首次登陆后，直接接收已经在线的user列表
    socket.on('allUser', function (data) {
        console.log('allUser 111 --');
        console.log(data);

        if (!$scope.loginInfo.hasLogined) return;
        /* 先去掉 friends 部分
         console.log('allUser 111 --');
         console.log($scope.friends);
         console.log(data);
         $scope.users = $scope.friends.concat(data) ;
         //console.log('allUser 222 --');
         console.log($scope.users);
         */


        $scope.users = data;
    });

    //接收到用户退出消息 ---- 这是其他人的离开结果，本地的 user 列表中删除掉该 user
    socket.on('userRemoved', function (data) {
        console.log('userRemoved 123 -data--');
        console.log(data);

        if (!$scope.loginInfo.hasLogined) return;
        $scope.publicMessages.push({content: " " + data.nickname + " ", type: "bye"});
        for (var i = 0; i < $scope.users.length; i++) {
            if ($scope.users[i].userName == data.userName) {
                //删除该元素
                $scope.users.splice(i, 1);
                return;
            }
        }
    });

    //接收到新消息
    socket.on('messageAdded', function (data) {
        console.log('messageAdded 111 ==');
        console.log(data);
        if (!$scope.loginInfo.hasLogined) return;

        //改用 toID 判断,to 空怎么判断不对呢?
        if (data.to != 'all') { //私信
            if (!$scope.privateMessages[data.from]) {
                $scope.privateMessages[data.from] = [];
            }

            //add by wzh 20160531 收到的消息,friend = from
            data.friend = data.from;

            $scope.privateMessages[data.from].push(data);

            //add by wzh 20160509 保存到 IDB
            if ($scope.useIDB)
                IDBService.saveMessages(data);
            else
                setPrivateMessagesToLS($scope.loginInfo.userName, data.from, $scope.privateMessages[data.from]);
            //localStorageService.set(messageID789, $scope.privateMessages[data.from]);

        } else {//群发
            $scope.publicMessages.push(data);
            var messageID234 = "message_all";
            //messageID234 = messageID234 + 'all';
            //add by wzh 20160509 保存到 IDB
            if ($scope.useIDB)
                IDBService.saveMessages(data);
            else
                setPublicMessagesToLS($scope.publicMessages);
            //localStorageService.set(messageID234, $scope.publicMessages);
        }

        var fromUser = userService.get($scope.users, data.from, data.from);
        var toUser = userService.get($scope.users, data.to, data.to);
        console.log('data.from ==' + data.from);
        console.log(fromUser);
        console.log('data.to ==' + data.to);
        console.log(toUser);

        if ($scope.receiver.userName !== data.to) {//与来信方不是正在聊天当中才提示新消息
            if (fromUser.userName != 'all' && toUser.userName != 'all') {
                fromUser.hasNewMessage = true;//私信
            } else {
                toUser.hasNewMessage = true;//群发
            }
        }

        //add by wzh 20160513 保存到friends
        if (isInFriends(fromUser.userName, $scope.friends)) {
            console.log('老朋友啊 ==');
            //do nothing
        }
        else {
            console.log('新人 ==');
            userService.setFriends($scope.loginInfo.userName, $scope.friends);
        }
    });

    //add by wzh 20160531 加上socket 其他事件
    //不是必须,方便测试程序
    socket.on('connect', function (res) {
        console.debug("connect 连接成功");
        console.log(res);
        $scope.disconnected = false;
        $scope.myPlaceHoder = "说点儿什么呢?";
    });


    socket.on('disconnect', function (res) {
        console.debug("disconnect 断开");
        console.log(res);
        $scope.disconnected = true;
        $scope.myPlaceHoder = "说不了了!等等吧......";

        Popup.alert('disconnect 断开啦 >>>>>> ', function () {
            console.log('知道了');
        });

    });

    //什么时候才会出来?重连多少次?多少时间?
    socket.on('connect_failed', function (res) {
        console.debug("connect_failed 连不上");
        console.log(res);

        $scope.disconnected = true;
        $scope.myPlaceHoder = "说不了了!等等吧......";

        Popup.alert('connect_failed 连不上 >>>>>> ', function () {
            console.log('知道了');
        });
    });

    socket.on('error', function (res) {
        console.debug("error 出错了");
        console.log(res);
        $scope.disconnected = true;
        $scope.myPlaceHoder = "说不了了!等等吧......";
    });

    socket.on('reconnect', function (res) {
        console.debug("reconnect 重新连成功");
        console.log(res);
        $scope.disconnected = false;
        $scope.myPlaceHoder = "说点儿什么呢?";

        Popup.alert('reconnect 重新连成功 >>>>>> ', function () {
            console.log('知道了');
        });
    });

    //判断某个userName是否存在于friends
    function isInFriends(name, friends) {
        for (i in friends) {
            if (name == friends[i].userName)
                return true;
        }
        //如果循环完成到这里,一定是不存在
        return false;
    }

    //消息读写 LS 处理的公用函数
    function setPrivateMessagesToLS(from, to, value) {
        var item = "message_" + from + "_with_" + to;
        localStorageService.set(item, value);
    };

    function getPrivateMessagesFromLS(from, to) {
        var result = [];
        var item = "message_" + from + "_with_" + to;
        var value = localStorageService.get(item);
        var x = angular.fromJson(value);
        if (x instanceof Array) {
            //console.log("x.length === " + x.length);
            for (var i = 0; i < x.length; i++) {
                //console.log(x[i]);
                result.push(x[i]);
            }
        }

        return result;
    };

    function setPublicMessagesToLS(value) {
        var item = "message_all"
        localStorageService.set(item, value);
    };

    function getPublicMessagesFromLS() {
        var result = [];
        var item = "message_all";
        var value = localStorageService.get(item);
        var x = angular.fromJson(value);

        if (x instanceof Array) {
            for (var i = 0; i < x.length; i++)
                result.push(x[i]);
        }

        return result;
    };


};

